<?php

namespace App\Http\Logic\PC;

use App;
use App\Helper\Helper;
use Illuminate\Support\Facades\DB;
use App\Models\Business;
use App\Models\Job;
use App\Common\Status;


class BusinessLogic
{
    public static function getBusiness($params, $pageSize, $page)
    {
        $businessIds = [];

        $where = [['a.show', '=', 2], ['a.status', '=', 1], ['a.is_deleted', '=', Status::NOT_DELETE]];

        if (isset($params['city']) && $params['city']) {
            $cityData = DB::table("recruit_business_address")->where(
                [
                    ["city", '=', $params['city']],
                    ["status", '=', Status::REGULAR],
                    ["is_deleted", '=', Status::NOT_DELETE],
                ]
            )->select(["business_id", "city", "area"])
                ->distinct("business_id")
                ->get();

            if (!$cityData->isEmpty()) {
                $businessIds = $cityData->pluck("business_id");
            }
        }

        if (isset($params['scale']) && $params['scale']) {
            $where[] = ['a.scale', '=', $params['scale']];
        }

        if (isset($params['type']) && $params['type']) {
            $where[] = ['a.type', '=', $params['type']];
        }

        if (isset($params['hot']) && $params['hot']) {
            $where[] = ['a.hot', '=', $params['hot']];
        }

        if (isset($params['name']) && $params['name']) {
            $where[] = ['a.name', 'like', '%' . $params['name'] . '%'];
        }


        $field = [
            "a.id", "a.name", "a.short_name", "a.logo", "a.logo2", "a.scale", "a.type", "a.content", "a.hot", "c.path"
        ];

        $data = DB::table('recruit_business as a')
            ->leftJoin('recruit_resources as c', function ($join) {
                $join->on("a.logo", "=", "c.id")
                    ->where("c.status", '=', Status::REGULAR)
                    ->where("c.is_deleted", '=', Status::NOT_DELETE);
            })->select($field)
            ->where($where)
            ->when($businessIds, function ($query, $businessIds) {
                return $query->whereIn("a.id", $businessIds);
            })
            ->orderBy("a.created_at", "desc")
            ->offset($pageSize * ($page - 1))
            ->limit($pageSize)
            ->get();
        $data = ($data->map(function ($value) {
            return (array)$value;
        })->toArray());


        $res   = self::getDataInfo($data);
        $count = self::getCount($where, $businessIds);
        return ['list' => $res, 'total' => $count, 'page' => $page, 'pageSize' => $pageSize];
    }

    private static function getCount($where, $businessIds)
    {
        return DB::table('recruit_business as a')
            ->leftJoin('recruit_resources as c', function ($join) {
                $join->on("a.logo", "=", "c.id")
                    ->where("c.status", '=', Status::REGULAR)
                    ->where("c.is_deleted", '=', Status::NOT_DELETE);
            })
            ->where($where)
            ->when($businessIds, function ($query, $businessIds) {
                return $query->whereIn("a.id", $businessIds);
            })
            ->count();
    }

    /**
     * 详情
     * @param $id
     * @return mixed
     */
    public static function getBusinessDt($id)
    {
        $field = ["a.id", "a.name", "a.short_name", "a.logo", "a.logo2", "a.scale", "a.type", "a.content", "a.hot", "c.path"];

        $data = DB::table('recruit_business as a')
            ->leftJoin('recruit_resources as c', function ($join) {
                $join->on("a.logo", "=", "c.id")
                    ->where("c.status", '=', Status::REGULAR)
                    ->where("c.is_deleted", '=', Status::NOT_DELETE);
            })->select($field)
            ->where("a.id", $id)
            ->get();
        $data = ($data->map(function ($value) {
            return (array)$value;
        })->toArray());

        return self::getDataInfo($data);
    }

    private static function getDataInfo($data)
    {
        $cond = function ($stu, $dtl, $bid) {
            return [
                ["business_id", $bid],
                ["status", $stu],
                ["is_deleted", $dtl]
            ];
        };
        foreach ($data as &$datum) {
            $address          = DB::table('recruit_business_address')->select(["area_name", "city_name"])
                ->where($cond(Status::REGULAR, Status::NOT_DELETE, $datum['id']))->get();
            $datum['address'] = $address ?: '';

            # 在招聘职位数量
            $datum['num'] = DB::table('recruit_job')
                ->where($cond(Status::PASS, Status::NOT_DELETE, $datum['id']))->count();

            $first              = DB::table('recruit_job')->where($cond(Status::PASS, Status::NOT_DELETE, $datum['id']))
                ->orderBy("created_at", "desc")
                ->first();
            $datum['first_job'] = $first ?: [];

            $datum["logo_path2"] = "";

            if($datum['logo2']) {
                $logo_path2 = DB::table('recruit_resources')->where("id",$datum['logo2'])->first();
                if ($logo_path2) {
                    $datum["logo_path2"] = $logo_path2->path;
                }
            }

            # 企业
            $datum['business_hot_info'] = $datum['hot'] == 1 ? '否' : '是';
            $datum['business_scale']    = Status::BUSINESS_SCALE[$datum['scale']];
            $datum['business_type']     = Status::BUSINESS_TYPE[$datum['type']];
            $datum['path']              = Helper::buildQiNiuUrl($datum['path']);
            $datum['logo_path2']              = $datum['logo_path2']?Helper::buildQiNiuUrl($datum['logo_path2']):"";
        }

        # 获取热门课程
        $hotCourse = DB::table('gz_goods')->select(["goods_sn", "goods_name", "price", "thumb", "goods_category"])
            ->where(
                [
                    ["is_hot", 1],
                    ["closed", '=', 0],
                    ["is_enable", '=', 1]
                ]
            )->get();

        return ["data" => $data, "hotCourse" => $hotCourse, "website_host" => env('WEBSITE_HOST')];
    }

    /**
     * 企业在招职位列表
     * @param $id
     * @return \Illuminate\Support\Collection
     */
    public static function getRecruitList($id, $hot)
    {
        $field   = [
            "a.id", "a.business_id", "a.position_custom_name", "a.position_category_child_id", "a.work_exp",
            "a.education", "a.salary1", "a.salary2", "a.salary_month", "a.welfare",
            "a.city", "a.area", "a.email", "a.release", "a.release_job", "a.job_type",
            "a.release_mobile", "a.describe", "a.hot", "b.name", "b.short_name",
            "b.logo", "b.scale", "b.type", "b.content", "b.hot", "c.path"
        ];
        $where[] = ['a.business_id', '=', $id];

        if ($hot == 2) {
            $where[] = ['a.hot', '=', $hot];
        }

        $where[] = ['a.status', '=', Status::PASS];
        $where[] = ["a.is_deleted", '=', Status::NOT_DELETE];

        $data = DB::table('recruit_job as a')
            ->leftJoin('recruit_business as b', function ($join) {
                $join->on("a.business_id", "=", "b.id")
                    ->where("b.show", '=', Status::PASS);
            })->leftJoin('recruit_resources as c', function ($join) {
                $join->on("b.logo", "=", "c.id")
                    ->where("c.status", '=', Status::REGULAR)
                    ->where("c.is_deleted", '=', Status::NOT_DELETE);
            })->select($field)->where($where)
            ->get();

        $r = [];
        if ($data) {
            $r = JobLogic::getDataInfo($data);
        }
        return $r;
    }

}
